package com.qdc.datacenters.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qdc.datacenters.client.ChatMsgAuditClient;
import com.qdc.datacenters.client.CorpUserClient;
import com.qdc.datacenters.domain.entity.BaseEntity;
import com.qdc.datacenters.domain.entity.CorpPermitUser;
import com.qdc.datacenters.domain.entity.SysCorp;
import com.qdc.datacenters.domain.entity.SysUser;
import com.qdc.datacenters.domain.query.BaseQuery;
import com.qdc.datacenters.domain.query.chatmsg.ChatMsgListQuery;
import com.qdc.datacenters.domain.query.corp.SysCorpQuery;
import com.qdc.datacenters.domain.query.qw.QwMsgAuditQuery;
import com.qdc.datacenters.domain.query.qw.QwUserQuery;
import com.qdc.datacenters.domain.query.user.CorpPermitUserQuery;
import com.qdc.datacenters.domain.vo.chatmsg.ChatMsgUserListVo;
import com.qdc.datacenters.domain.vo.qw.QwMsgAuditVo;
import com.qdc.datacenters.domain.vo.qw.QwUserDetailVo;
import com.qdc.datacenters.enums.DeleteStatusEnum;
import com.qdc.datacenters.enums.QwErrorCodeEnum;
import com.qdc.datacenters.exception.CommonException;
import com.qdc.datacenters.mapper.CorpPermitUserMapper;
import com.qdc.datacenters.service.ICorpPermitUserService;
import com.qdc.datacenters.service.ISysCorpService;
import com.qdc.datacenters.service.ISysUserService;
import com.qdc.datacenters.utils.SecurityUtils;
import com.qdc.datacenters.utils.StrUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 开通会话存档员工信息(CorpPermitUser)表服务实现类
 *
 * @author danmo
 * @since 2024-03-04 11:15:05
 */
@Slf4j
@Service
public class CorpPermitUserServiceImpl extends BaseServiceImpl<CorpPermitUserMapper, CorpPermitUser> implements ICorpPermitUserService {

    @Autowired
    private ISysUserService iSysUserService;
    @Resource
    private CorpUserClient userClient;
    @Resource
    private ChatMsgAuditClient chatMsgAuditClient;

    @Autowired
    private ISysCorpService iSysCorpService;

    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public List<ChatMsgUserListVo> getUserMsgList(ChatMsgListQuery query) {
        return this.baseMapper.getUserMsgList(query);
    }

    @Override
    public CorpPermitUser getByCorpUserId(String corpUserId) {
        CorpPermitUser permitUser = null;
        try {
            if (!lock.tryLock(3, TimeUnit.SECONDS)) {
                return permitUser;
            }
        } catch (InterruptedException e) {
            log.error("get user error msg:{}", e.getMessage(), e);
            return permitUser;
        }
        try {
            permitUser = getOne(new LambdaQueryWrapper<CorpPermitUser>()
                    .eq(CorpPermitUser::getCorpUserId, corpUserId)
                    .eq(CorpPermitUser::getDelFlag, DeleteStatusEnum.DELETE_NO.getIndex())
                    .last("limit 1"));
            if (Objects.isNull(permitUser)) {
                QwUserQuery userQuery = new QwUserQuery();
                userQuery.setUserid(corpUserId);
                QwUserDetailVo userDetail = userClient.getUserInfo(userQuery);
                if (Objects.nonNull(userDetail) && Objects.equals(0, userDetail.getErrCode())) {
                    CorpPermitUser addPermitUser = getPermitUser(userDetail);
                    if (save(addPermitUser)) {
                        permitUser = addPermitUser;
                    }
                }
            }
        } catch (Exception e) {
            log.error("get user error msg:{}", e.getMessage(), e);
            return permitUser;
        } finally {
            lock.unlock();
        }

        return permitUser;
    }


    @Override
    public void sync(BaseQuery query) {
        SysCorp sysCorp = iSysCorpService.get(new SysCorpQuery());
        if (Objects.isNull(sysCorp)) {
            throw new CommonException("企业未配置");
        }
        if (StrUtils.isEmpty(sysCorp.getCorpId())) {
            throw new CommonException("企业ID未配置");
        }
        if (StrUtils.isEmpty(sysCorp.getAgentSecret())) {
            throw new CommonException("应用密钥未配置");
        }
        if (StrUtils.isEmpty(sysCorp.getChatSecret())) {
            throw new CommonException("会话密钥未配置");
        }
        QwMsgAuditQuery msgAuditQuery = new QwMsgAuditQuery();
        QwMsgAuditVo permitUserList = chatMsgAuditClient.getPermitUserList(msgAuditQuery);
        if (Objects.isNull(permitUserList)) {
            throw new CommonException("企微同步接口调用失败");
        }
        if (!Objects.equals(0, permitUserList.getErrCode())) {
            throw new CommonException(permitUserList.getErrCode(), QwErrorCodeEnum.parseEnum(permitUserList.getErrCode()).getErrorMsg());
        }
        List<String> corpUserIds = permitUserList.getIds();
        if (CollectionUtil.isEmpty(corpUserIds)) {
            throw new CommonException("企微未设置范围内的成员");
        }
        for (String corpUserId : corpUserIds) {
            ThreadUtil.execute(() -> {
                getByCorpUserId(corpUserId);
            });
        }
    }

    @Override
    public List<CorpPermitUser> getList(CorpPermitUserQuery query) {
        return this.baseMapper.getList(query);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        if (Objects.isNull(id)) {
            throw new CommonException("ID不能为空");
        }
        if (Objects.isNull(status)) {
            throw new CommonException("状态不能为空");
        }
        CorpPermitUser permitUser = new CorpPermitUser();
        permitUser.setStatus(status);
        permitUser.setId(id);
        updateById(permitUser);
    }

    @Override
    public void delete(CorpPermitUserQuery query) {
        Optional.ofNullable(query.getIds()).orElseGet(ArrayList::new).add(query.getId());
        if (!CollectionUtils.isEmpty(query.getIds())) {
            update(new LambdaUpdateWrapper<CorpPermitUser>()
                    .set(BaseEntity::getDelFlag, DeleteStatusEnum.DELETE_YES.getIndex())
                    .set(CorpPermitUser::getUpdateTime, new Date())
                    .set(CorpPermitUser::getUpdateBy, SecurityUtils.getUserId())
                    .in(CorpPermitUser::getId, query.getIds()));
        }
    }

    private CorpPermitUser getPermitUser(QwUserDetailVo userDetail) {
        SysUser sysUser = iSysUserService.getByCorpUserId(userDetail.getUserId());
        CorpPermitUser permitUser = new CorpPermitUser();
        permitUser.setCorpUserId(userDetail.getUserId());
        permitUser.setCorpUserName(userDetail.getName());
        if (Objects.nonNull(sysUser)) {
            permitUser.setUserId(sysUser.getUserId());
        }
        permitUser.setAvatar(userDetail.getAvatar());
        permitUser.setAlias(userDetail.getAlias());
        permitUser.setGender(userDetail.getGender());
        permitUser.setMobile(userDetail.getMobile());
        return permitUser;
    }
}

